/**
 * LayerManager.js
 * Version: 1.0
 * Author: lmc
 *
 */

 //全局符号化对象
var _styles = {
    'XZQ': new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: 'rgba(255,0,0,0.8)',
        width: 1
      }),
      fill: new ol.style.Fill({
        color: 'rgba(0,255,255,0.1)'
      }),
      text: new ol.style.Text({ //文本样式
        font: 'bold 14px serif',
        overflow: true,
        fill: new ol.style.Fill({
          color: 'rgba(0,0,0,1)'
        }),
        stroke: new ol.style.Stroke({
          color: 'rgba(255,255,255,0.5)',
          width: 3
        })
      })
    }),
    'star': new ol.style.Style({
      image: new ol.style.Icon({
        src: 'img/star.png'
      }),
      text: new ol.style.Text({ //文本样式
        font: 'bold 14px serif',
        overflow: true,
        fill: new ol.style.Fill({
          color: 'rgba(0,0,0,1)'
        }),
        stroke: new ol.style.Stroke({
          color: 'rgba(255,255,255,0.5)',
          width: 3
        })
      })
    }),
    'POI': new ol.style.Style({
        image: new ol.style.Circle({
            radius: 4,
            stroke: new ol.style.Stroke({
                color: 'rgba(0,111,255,1)'
            }),
            fill: new ol.style.Fill({
                color: 'rgba(0,111,255,1)'
            })
        }),
        text: new ol.style.Text({ //文本样式
            font: 'bold 13px serif',
            overflow: true,
            fill: new ol.style.Fill({
                color: '#ff0000'
            }),
            stroke: new ol.style.Stroke({
                color: '#fff',
                width: 3
            })
        })
    }),
    'Point': new ol.style.Style({
       image: new ol.style.Circle({
            radius: 6,
            stroke: new ol.style.Stroke({
                color:'rgba(255,0,0,1)'
            }),
            fill: new ol.style.Fill({
                color: 'rgba(255,0,0,1)'
            })
        }),
        text: new ol.style.Text({ //文本样式
        font: 'bold 14px serif',
        overflow: true,
        fill: new ol.style.Fill({
          color: 'rgba(0,0,0,1)'
        }),
        stroke: new ol.style.Stroke({
          color: 'rgba(255,255,255,0.5)',
          width: 3
        })
      })
    }),
    'Line': new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: 'rgba(0,0,255,1)',
        width: 2
      })
    }),
    'Railway1':new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: 'rgba(0,0,0,1)',
        lineCap:'square',
        width: 3
      })
    }),
    'Railway2': new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: 'rgba(255,255,255,1)',
        lineCap:'square',
        lineDash: [10,14],
        width: 3
      })
    })
    
};

//铁路符号化函数
var _styleRailwayFunction1=function(feature,resolution){
    return _styles['Railway1'];
}

var _styleRailwayFunction2=function(feature,resolution){
    return _styles['Railway2'];
}

var _railwayStyles=[
  _styleRailwayFunction1,
  _styleRailwayFunction2
];

function wrapLongString(mystr) {
   if(mystr.length<5){
     return mystr;
   }else{
     return mystr.substr(0,4)+'\n'+mystr.substr(4);
   }
}

//line符号化函数
var _styleLineFunction = function(feature,resolution) {
   var tmpstyle=_styles['Line'];
   return tmpstyle;
}

//xzq符号化函数
var _styleXZQFunction = function(feature,resolution) {
   var tmpstyle=_styles['XZQ'];
   tmpstyle.getText().setText(feature.get('NAME'));
   return tmpstyle;
}

//point符号化函数
var _stylePointFunction = function(feature,resolution) {
   var tmpstyle=_styles['Point'];
   if(resolution <19.2 ){
        var offsetX = feature.get('NAME').length * 3;
        var text = tmpstyle.getText();
        text.setOffsetX(offsetX);
        text.setOffsetY(-14);
        text.setText(wrapLongString(feature.get('NAME')));
   }else{
      tmpstyle.getText().setText('');
   }
   return tmpstyle;
}

//POI符号化函数
var _stylePOIFunction = function(feature,resolution) {
   var tmpstyle=_styles['POI'];
   var offsetX = feature.get('NAME').length * 3;
   var text = tmpstyle.getText();
   text.setOffsetX(offsetX);
   text.setOffsetY(-13);
   text.setText(wrapLongString(feature.get('NAME')));
   return tmpstyle;
}

//聚合符号化缓存
var _styleCache = {};

//bigLayer全局变量，用来存放大数据图层
_bigVectorLayer=[];
function _onExtentUpdate(evt) {
    if(map.getView().getZoom()<15|| _bigVectorLayer.length==0){
        return;
    }
    var polygon=ol.geom.Polygon.fromExtent(map.getView().calculateExtent(map.getSize()));
    var polygonWKT=(new ol.format.WKT()).writeGeometry(polygon,{
        dataProjection: 'EPSG:4326',
        featureProjection: 'EPSG:3857'
      });
    for(var i=0;i<_bigVectorLayer.length;i++){
        var vectorExtentLayer=_bigVectorLayer[i];
        if(vectorExtentLayer.getVisible()==false){
            continue;
        }
        //删除旧数据
        if(vectorExtentLayer.getSource()!=null){
             vectorExtentLayer.getSource().clear();
        }
        var myurl=vectorExtentLayer.getSource().getUrl();
        if(myurl.indexOf('&')>0){
           myurl=myurl.substr(0,myurl.indexOf('&'));
        }
        
        myurl=myurl+"&wkt="+polygonWKT+'&level='+map.getView().getZoom();
        vectorExtentLayer.setSource(new ol.source.Vector({
                     url:myurl,
                     format: new ol.format.GeoJSON()
        }));
    } 
}
      
map.on('moveend',_onExtentUpdate);

var LayerManager = function () {

    this.addPointLayer = function (layerTitle,layerUrl,layerStyle) {
        //设置参数style的默认值
        var pointStyle=arguments[2] ? arguments[2] : _stylePointFunction;
        var vectorPointLayer = new ol.layer.Vector({
            title: layerTitle,
            visible:true,
            source: new ol.source.Vector({
                         url: layerUrl,
                         format: new ol.format.GeoJSON()
                    }),
            style: pointStyle,
            declutter: false
        });
        YWLayer.getLayers().push(vectorPointLayer);
    };
    
    this.addPolylineLayer = function (layerTitle,layerUrl,layerStyle) {
         //设置参数style的默认值
        var polylineStyle= arguments[2] ? arguments[2] :_styleLineFunction;
         var vectorPolylineLayer = new ol.layer.Vector({
            title: layerTitle,
            visible:true,
            source: new ol.source.Vector({
                         url: layerUrl,
                         format: new ol.format.GeoJSON()
                    }),
            style: polylineStyle,
            declutter: false
        });
        YWLayer.getLayers().push(vectorPolylineLayer);
    };
    
    this.addPolygonLayer = function (layerTitle,layerUrl,layerStyle) {
         //设置参数style的默认值
        var polygonStyle= arguments[2] ? arguments[2] : _styleXZQFunction;
        var vectorPolygonLayer = new ol.layer.Vector({
            title: layerTitle,
            visible:true,
            source: new ol.source.Vector({
                         url: layerUrl,
                         format: new ol.format.GeoJSON()
                    }),
            style: polygonStyle,
            declutter: false
        });
        YWLayer.getLayers().push(vectorPolygonLayer);
    };
    
    this.addBigLayer=function (layerTitle,layerUrl,geomType,layerStyle) {
         //设置参数style的默认值
        var bigStyle=null;
        if(arguments[3]){
            bigStyle=arguments[3];
        }else{
           if(geomType=='Polygon'){
              bigStyle=_styleXZQFunction;
           }else if(geomType=='Polyline'){
              bigStyle=_styleLineFunction;
           }else if(geomType=='Poinr'){
              bigStyle=_stylePointFunction;
           }
        }
        var vectorBigLayer = new ol.layer.Vector({
            title: layerTitle,
            visible:true,
            source: new ol.source.Vector({
                         url: layerUrl,
                         format: new ol.format.GeoJSON()
                    }),
            style: bigStyle,
            declutter: false
        });
        YWLayer.getLayers().push(vectorBigLayer);
        _bigVectorLayer.push(vectorBigLayer);
    };
    
    this.addClusterLayer = function (layerTitle,layerUrl,layerStyle) {
        //设置参数style的默认值
            var clusterStyle=arguments[2] ? arguments[2] :_stylePOIFunction;
                var _tmpStyleClusterFunction = function (feature, resolution) {
                var size = feature.get('features').length;
                if (size > 1) {
                    var style = _styleCache[size];
                    if (!style) {
                        style = new ol.style.Style({
                            image: new ol.style.Circle({
                                radius: 14,
                                stroke: new ol.style.Stroke({
                                    color: '#fff'
                                }),
                                fill: new ol.style.Fill({
                                    color: '#3399CC'
                                })
                            }),
                            text: new ol.style.Text({
                                text: size.toString(),
                                fill: new ol.style.Fill({
                                    color: '#fff'
                                })
                            })
                        });
                        _styleCache[size] = style;
                    }
                    return style;
                } else {
                    var originalFeature = feature.get('features')[0];
                    return clusterStyle(originalFeature, resolution);
                }
            };
            var vectorPOISource = new ol.source.Vector({
                         url: layerUrl,
                         format: new ol.format.GeoJSON()
            });
                
            var clusterSource = new ol.source.Cluster({
                distance: 25,
                source: vectorPOISource
            });
                    
            var vectorPOILayer = new ol.layer.Vector({
                title: layerTitle+'原始',
                visible:true,
                maxResolution: 2.4,
                source: vectorPOISource,
                style: clusterStyle,
                declutter: false
            });

            var vectorPOIClusterLayer = new ol.layer.Vector({
                title: layerTitle+'聚合',
                visible: true,
                minResolution: 2.4,
                source: clusterSource,
                style: _tmpStyleClusterFunction,
                declutter: false
            });
             YWLayer.getLayers().push(vectorPOILayer);
             YWLayer.getLayers().push(vectorPOIClusterLayer);
    };
    
    this.addCompositeLayer=function (layerTitle,layerUrl,layerStyles){
         //设置参数style的默认值,参数是数组
            var compositeStyles=arguments[2] ? arguments[2] :_railwayStyles;
            var vectorSource = new ol.source.Vector({
                         url: layerUrl,
                         format: new ol.format.GeoJSON()
            });
            for(var i=0;i<compositeStyles.length;i++){
                var vectorLayer = new ol.layer.Vector({
                    title: layerTitle+i,
                    visible:true,
                    source: vectorSource,
                    style: compositeStyles[i],
                    declutter: false
                });
                YWLayer.getLayers().push(vectorLayer);
            }

    };
    
    this.addTileLayer = function (layerTitle,layerUrl) {
        var tileLayer= new ol.layer.Tile({
                          title:layerTitle,
                          visible:true,
                          source:new ol.source.XYZ({url:layerUrl})
                        });
        YWLayer.getLayers().push(tileLayer);
    };
    
    this.removeVectorLayer = function (layerTitle) {
        YWLayer.getLayers().remove(getLayerByTitle(layerTitle));
        _bigVectorLayer.remove(getLayerByTitle(layerTitle));
    };
    
    this.removeClusterLayer = function (layerTitle) {
        YWLayer.getLayers().remove(getLayerByTitle(layerTitle+'原始'));
        YWLayer.getLayers().remove(getLayerByTitle(layerTitle+'聚合'));
    };
    
    this.removeCompositeLayer = function (layerTitle,layerCount) {
        for(var i=0;i<layerCount;i++){
            YWLayer.getLayers().remove(getLayerByTitle(layerTitle+i));
        }
    };
    
    this.getVectorLayer = function (title) {
        return getLayerByTitle(title);
    };
    
    this.setVectorLayerVisible = function (title,isVisible) {
        getLayerByTitle(title).setVisible(isVisible);
    };
    
    this.setClusterLayerVisible = function (title,isVisible) {
        getLayerByTitle(title+'原始').setVisible(isVisible);
        getLayerByTitle(title+'聚合').setVisible(isVisible);
    };
    
}